package com.dalin.platform.loa.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;

import com.dalin.common.PropertyConst;
import com.dalin.common.utils.StringUtils;
import com.dalin.framework.action.StrutsTwoAction;
import com.dalin.platform.loa.LoaConst;

/*****************************************************************************
 * @content: 代码表查询公用action                                             *
 * @author : 那建林                                                          *
 * @crtDate: 2009-05-19                                                     *
 ****************************************************************************/
public class RandomAuthenticodeAction extends StrutsTwoAction {
	public String execute() throws Exception {
		getRes().setContentType("image/jpeg");
		getRes().setHeader("Pragma", "No-cache");
		getRes().setHeader("Cache-Control", "no-cache");
		getRes().setDateHeader("ExpigetRes()", 0);
		
		int iWidth = 80; // 设置图片宽度
		int iHeight = 25; // 设置图片高度
		// 在内存中创建图象
		BufferedImage image = new BufferedImage(iWidth, iHeight,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics(); // 获取图形上下文
		// 设定背景色
		g.setColor(new Color(0xDCDCDC));
		g.fillRect(0, 0, iWidth, iHeight);
		g.setFont(new Font("Atlantic Inline", Font.PLAIN, 18));
		// 画边框
		g.setColor(Color.black);
		g.drawRect(0, 0, iWidth - 1, iHeight - 1);

		Random random = new Random();
		// 随机产生的4位数字认证码
		String[] randArray = StringUtils.getRandomStrArray(PropertyConst.ARRAY_DIGIT, 4);
		// 将认证码显示到图象中
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < randArray.length; i++) {
			sb.append(randArray[i]);
			g.drawString(randArray[i], 15 * (i + 1), 15 + random.nextInt(10));
		}
		
		// 将认证码存入SESSION
		HttpSession session = getReq().getSession();
		session.setAttribute(LoaConst.RANDOM_AUTHENTICODE_SESSION_NAME, sb.toString());
		session.setMaxInactiveInterval(LoaConst.RANDOM_AUTHENTICODE_EXPIRE); // 验证码有效期为60秒
		
		// 随机产生干扰点，使图象中的认证码不易被其它程序探测到
		for (int i = 0; i < 40; i++) {
			int x = random.nextInt(iWidth);
			int y = random.nextInt(iHeight);
			g.drawOval(x, y, 0, 0);
		}
		// 图象生效
		g.dispose();
		ImageIO.write(image, "JPEG", getRes().getOutputStream());
		return null;
	}
}
